#!/usr/bin/env python
# $Id: test2-47.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

def compress(hextets):
   if len(hextets) == 8:
      start = -1
      end = -1
      bstart = -1
      bend = -1
      count = 0
      for ix in hextets:
         value = int(ix, 16)
         if value == 0:
            if start == -1:
               start = count

            if start >= 0:
               end = count
               bstart = start
               bend = end
         else:
            if start >= 0:
               start = -1

            if end >= 0:
               end = -1

         count += 1

      count = 0
      print(bstart, bend)
      hextets[bstart:(bend + 1)] = ['']
      address = ":".join(hextets)
      if len(address):
         if address[-1] == ":":
            address += ":"
      else:
         address = "::"

      return address

def test(address):
   if len(address):
      (network, prefix) = address.split("/")
      network = "%s/%s" %(compress(network.split(":")), prefix)
      print(network)

test("2001:0500:0000:ffcf:0000:0000:0000:0000/64")
test("fe80:0000:0000:0000:215:c5ff:fe78:5fb6/64")
test("0000:0000:0000:0000:0000:0000:0000:0000/3")
test("2001:0000:0000:ffde:abcd:edab:cdef:abcd/64")
test("2001:1868:209:abdc:abdc:0000:0000:defc/64")
test("0000:0000:0000:0000:0000:0000:0000:1/128")
